The COVID-19 pandemic is a one off global event. It has sent shockwaves to economies across the globe. Similarly, other global crises have affected the market in ways that were previously unforeseen. In this project, we aim to perform an in-depth analysis of the impact of the COVID-19 pandemic, as well as global crises such as the Ukraine War, on the performance of the top 5 stocks within four sectors that were severely affected by the crisis. The four sectors we are focusing on are Tech, Pharma, Telecom and FMCG (Fast moving consumer goods) and only on US stocks for this. This analysis is pivotal in understanding how economic crises impact stock performance and the broader financial markets. The study will be conducted in a Jupyter Notebook environment using statistical models and is expected to span a duration of 40-45 days.
In a more specific sense, creating these analyses may help us provide contextual and researched advice to investors that may want to invest in major stocks, but want to minimize risk. There is no way to accurately predict how stocks will perform, particularly in a crisis, but our analysis can help inform those who plan to invest in these sectors how to handle their investments in the event of any type of crisis that introduces great risk.
In order to analyze stock performance throughout the pandemic and through the Ukraine War, we are pulling stock data from October 2019 to the current date. We will be taking a closer look at these dates listed below in order to hone in on the impacts from these specific events:
● How did economic shocks impact the price movements of the top 5 stocks in each sector?
● In what ways did these sectors respond to the challenges and opportunities posed?
● How to identify headwind /tailwind effect?
● To what extent did tech sector deviate from the expected behavior?
● Are there any anomalies that stand out?
● Is Tech sector witnessing a permanent paradigm shift?
We expect to gain valuable insights from our research on how different sectors and individual stocks responded to the impacts of the pandemic and the war. Our analysis aims to reveal patterns that show which sectors and stocks demonstrated resilience in the face of these external shocks and which ones proved vulnerable. Additionally, we will identify potential indicators that could predict how these sectors would react, whether in advance or with a delay. We plan to validate these patterns across various timeframes, depending on the results of our initial exploratory analysis. Ultimately, our findings are intended to offer important insights into how external shocks affect financial markets. These insights will serve as a valuable resource for investors and policymakers, helping them make more informed decisions in response to such events.
EDA to be done to infer more insights by digging deeper into our findings from the data.
We anticipate a potential significant decline in the FMCG (Fast-Moving Consumer Goods) stocks, while pharmaceutical stocks may have experienced an extraordinary surge. We intend to substantiate this hypothesis by analyzing the patterns that emerged during the lockdown period and exploring other prevalent trends both before and after the lockdown.
In the context of our project, we propose to be graded more heavily on data analysis rather than data processing. The reason for this choice is that we intentionally invested significant effort in ensuring the initial cleanliness and completeness of our dataset. The data was meticulously cleaned and organized prior to our analysis phase, eliminating the need for extensive data processing.
Our emphasis on data analysis stems from the recognition that, with a well-prepared dataset, we can delve deeply into the intricacies of the stock market and extract valuable insights. The analytical phase of our project involves the application of statistical and visualization techniques to uncover patterns, trends, and correlations within the stock data. By focusing on data analysis, we aim to go beyond basic analysis needs, exploring nuanced aspects that can provide investors with valuable information for making informed investment decisions.
In summary, while data processing laid the foundation by ensuring data quality, our unique contribution lies in the sophisticated data analysis techniques applied to the well-prepared dataset, aiming to provide investors with deeper insights and enhance the decision-making process.
The dataset will cover a specific time frame, aligning with the onset and duration of the COVID-19 pandemic, allowing us to capture the relevant period. The data stretches from October 2019. We will be combining the stock price data from 20 different stocks from 4 sectors, as well as the S&P 500 and Dow Jones into one dataset. Overall, we will have about 1,460 rows, 110 columns
and around 160,600 observations.
What variables are we looking at for each index and stock:
● Closing stock price - The price of the stock when the market closed that day.
● Opening stock price - The price of the stock when the market opened that day.
● High - The highest the price rose that day.
● Low - The lowest the price dipped that day.
● Adjusted Close - Amended close price based on any corporate actions.
● Traded Volume - Number of shares traded that day.
● Date
| Ticker | Name | Company Description | Mcap in $B | Industry |
|---|---|---|---|---|
| AAPL | Apple Inc. | Designs, develops,and sells consumer electronics, computer software, and online services | 2746.21 | Technology |
| AMZN | Amazon.com, Inc. | Onine retailer of a wide variety of products and services | 1084.06 | Technology |
| BMY | Bristol-Myers Squibb Company | Pharmaceutical company that develops and manufactures prescription medications. | 102.57 | Healthcare |
| CHTR | Charter Communications, Inc. | Cable television company that provides video, voice, and high-speed internet services. | 61.36 | Telecommunications |
| CL | Colgate-Palmolive Company | Consumer products company that manufactures and sells oral care, personal care, home care, and pet nutrition products. | 61.87 | Consumer Staples |
| CMCSA | Comcast Corporation | Cable television company that provides video, voice, and high-speed internet services. | 167.16 | Telecommunications |
| GOOG | Alphabet Inc. | Technology company that specializes in Internet-related services and products. | 1340.53 | Technology |
| JNJ | Johnson & Johnson | Pharmaceutical and medical devices company that develops and manufactures prescription medications, over-the-counter medications, medical devices, and consumer health products. | 354.88 | Healthcare |
| KO | The Coca-Cola Company | Beverage company that manufactures and sells non-alcoholic beverages. | 246.82 | Consumer Staples |
| LLY | Eli Lilly and Company | Pharmaceutical company that develops and manufactures prescription medications. | 565.07 | Healthcare |
| META | Meta Platforms, Inc. | Technology company that specializes in social networking, online advertising, and virtual reality. | 798.89 | Technology |
| MRK | Merck & Co., Inc. | Pharmaceutical company that develops and manufactures prescription medications. | 256.55 | Healthcare |
| MSFT | Microsoft Corporation | Technology company that develops, manufactures, licenses, supports, and sells computer software, computer hardware, consumer electronics, and personal computers, and related services. | 2309.84 | Technology |
| PEP | PepsiCo, Inc. | Beverage and food company that manufactures and sells soft drinks, snacks, and other food products. | 228.73 | Consumer Staples |
| PFE | Pfizer Inc. | Pharmaceutical company that develops and manufactures prescription medications. | 167.58 | Healthcare |
| PG | Procter & Gamble Company | Consumer products company that manufactures and sells personal care, household care, health care, and fabric and home care products. | 354.33 | Consumer Staples |
| T | AT&T Inc. | Telecommunications company that provides wireless, wireline, and video services. | 111.5 | Telecommunications |
| TMUS | T-Mobile US, Inc. | Wireless communications company that provides wireless voice, messaging, and data services. | 169.88 | Telecommunications |
| VZ | Verizon Communications Inc. | Telecommunications company that provides wireless, wireline, and video services. | 151.43 | Telecommunications |
| WMT | Walmart Inc. | Discount retailer that operates a chain of hypermarkets, discount department stores, and grocery stores. | 446.87 | Consumer Staples |
So far, we have been able to collect all of our data from Yahoo Finance (stocks) and MarketWatch (global indexes), and merge them together, as well as clean before creating our index values for each stock.
We first had to concatenate the stock data together, then the indexes before merging both to create a hierarchically indexed dataframe. We cleaned the data by reformatting the date/time index in order to match them up for the merging of the indexes and stocks. In this case, we do not need to replace missing values as they are useful in our analysis and indicate that the stock market was closed on that day.
In the realm of financial analysis, indexing plays a crucial role in harmonizing diverse metrics and facilitating meaningful comparisons. The process involves rescaling data to a common denominator, providing a standardized basis for evaluation. In the described scenario, two indexing methodologies are employed: equal weighted indexing and reindexing. Equal weighted indexing allocates a uniform 20% weight to each of the five stocks within the sector, effectively capturing industry-level effects. On the other hand, reindexing involves adjusting the base values of multiple stocks relative to each other, often setting them all to a common starting point, such as 100. This process allows for the observation of patterns and performance changes within a specified time frame. The equal weighted index offers a straightforward representation of sectoral dynamics by aggregating proportional contributions from each stock, while reindexing introduces a temporal dependency by aligning stock values to a previous time point. Both indexing methods contribute valuable insights for analyzing stock market behavior and sectoral trends over specific time intervals.
# importing Data Analysis & Visualization library
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
Each individual stock or global index data frame is created with previously downloaded csv files. Since it is a csv file, we separate based on a comma and because we want to look at the change over time, we are using the column 'Date' as our index.
# defining the file path. Change this according to your local system where you have placed your "DataFiles" folder containing the data tables
file_path = ''
file_names = ['AAPL.csv','AMZN.csv','BMY.csv','CL.csv','CMCSA.csv','GOOG.csv','JNJ.csv','KO.csv','CHTR.csv','LLY.csv','META.csv','MRK.csv','MSFT.csv','PEP.csv',
'PFE.csv','PG.csv','T.csv','TMUS.csv','VZ.csv','WMT.csv','S&P_Oct19-20.csv','S&P_Oct20-21.csv','S&P_Oct21-22.csv',
'S&P_Oct22-23.csv','DJIA_Oct19-20.csv','DJIA_Oct20-21.csv',
'DJIA_Oct21-22.csv', 'DJIA_Oct22-23.csv']
stock_data = dict();
#Loading data for all the stocks from the datafiles
for file in file_names:
stock_data[file.replace('.csv','')] = pd.read_csv(file_path + file, delimiter = ',', index_col = 'Date')
Because every single dataframe has the same named columns, we need to concatenate these dataframes and use keys in order to hierarchically index the different columns for each stock or index.
For our global index dataframes (S&P 500 and dow Jones), their data came in a format that included commas to indicate the number was in thousands. However, this did not match the data from the stocks, so we replaced each value that had a comma with nothing, and converted the values to floats so we could later do analysis on them.
Again for our global index dataframes, we set the index to be the date, while for our stocks dataframe, we used an inner join in order to concatenate on the date index for each stock (so there is only one date index).
#Creating s&p500 dataset
df500 = pd.concat([stock_data['S&P_Oct22-23'],stock_data['S&P_Oct21-22'],stock_data['S&P_Oct20-21'],stock_data['S&P_Oct19-20']])
df500 = df500.apply(lambda value: value.str.replace(',','').astype(float))
#creating Dow dataset
dfDow = pd.concat([stock_data['DJIA_Oct22-23'],stock_data['DJIA_Oct21-22'],stock_data['DJIA_Oct20-21'],stock_data['DJIA_Oct19-20']])
dfDow = dfDow.apply(lambda value: value.str.replace(',','').astype(float))
#creating merged dataset for all stocks
dfStocks = pd.concat({key : values for key,values in stock_data.items() if not (key.startswith('S&P') or key.startswith('DJIA'))},axis=1)
dfStocks.head()
| AAPL | AMZN | ... | VZ | WMT | |||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Open | High | Low | Close | Adj Close | Volume | Open | High | Low | Close | ... | Low | Close | Adj Close | Volume | Open | High | Low | Close | Adj Close | Volume | |
| Date | |||||||||||||||||||||
| 2019-10-23 | 60.525002 | 60.810001 | 60.305000 | 60.794998 | 59.128941 | 75828800.0 | 88.065002 | 88.502502 | 87.099998 | 88.108498 | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| 2019-10-24 | 61.127499 | 61.200001 | 60.452499 | 60.895000 | 59.226208 | 69275200.0 | 88.554497 | 89.417000 | 88.013496 | 89.039001 | ... | 60.410000 | 60.580002 | 49.041088 | 11143800.0 | 119.150002 | 119.570000 | 118.510002 | 119.099998 | 111.734749 | 2900300.0 |
| 2019-10-25 | 60.790001 | 61.682499 | 60.720001 | 61.645000 | 59.955658 | 73477200.0 | 84.877502 | 88.210503 | 84.750000 | 88.066498 | ... | 59.209999 | 60.369999 | 48.871086 | 15036400.0 | 119.000000 | 119.330002 | 118.199997 | 119.040001 | 111.678444 | 2564300.0 |
| 2019-10-28 | 61.855000 | 62.312500 | 61.680000 | 62.262501 | 60.556232 | 96572800.0 | 87.403000 | 88.934998 | 87.125000 | 88.853996 | ... | 60.040001 | 60.180000 | 48.717274 | 14621400.0 | 119.250000 | 119.699997 | 118.529999 | 119.220001 | 111.847305 | 3404600.0 |
| 2019-10-29 | 62.242500 | 62.437500 | 60.642502 | 60.822498 | 59.155693 | 142839600.0 | 88.740501 | 88.849998 | 87.790497 | 88.135498 | ... | 60.070000 | 60.189999 | 48.725368 | 10619900.0 | 118.500000 | 118.730003 | 117.080002 | 117.150002 | 109.905312 | 4791100.0 |
5 rows × 120 columns
Next, we merged all three datasets. First, we concatenated the two global indexes, once again, so that we could hierarchically index them, regardless of the fact that they have the same column names. We did an inner join on the date index so that there was only one date index.
dfIndexes = pd.concat((df500, dfDow), join ='inner', keys=['S&P500', 'DJIA30'],axis=1)
Before merging the stocks data and the indexes data, we needed to make sure that the datetime format matched up. The global indexes dataframe had a date index in month/day/year format, and we needed to convert this to year-month-date format, in order to make it the same as the stocks index.
dfIndexes.index = dfIndexes.index.map(lambda d: pd.to_datetime(d).strftime('%Y-%m-%d'))
dfIndexes.head()
| S&P500 | DJIA30 | |||||||
|---|---|---|---|---|---|---|---|---|
| Open | High | Low | Close | Open | High | Low | Close | |
| Date | ||||||||
| 2023-10-24 | 4235.79 | 4259.38 | 4219.43 | 4247.68 | 33089.64 | 33272.19 | 32988.43 | 33141.38 |
| 2023-10-23 | 4210.40 | 4255.84 | 4189.22 | 4217.04 | 32993.02 | 33234.85 | 32892.19 | 32936.41 |
| 2023-10-20 | 4273.85 | 4276.56 | 4223.03 | 4224.16 | 33365.27 | 33425.77 | 33118.12 | 33127.28 |
| 2023-10-19 | 4321.36 | 4339.54 | 4269.69 | 4278.00 | 33669.52 | 33852.39 | 33368.58 | 33414.17 |
| 2023-10-18 | 4357.35 | 4364.20 | 4303.84 | 4314.60 | 33960.25 | 33991.51 | 33598.64 | 33665.08 |
The values in the index dataframe were rounded to 2 decimal points, so we are doing the same thing to the stocks dataframe in order to help us with our analysis later.
dfStocks = dfStocks.round(1)
dfStocks.head()
| AAPL | AMZN | ... | VZ | WMT | |||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Open | High | Low | Close | Adj Close | Volume | Open | High | Low | Close | ... | Low | Close | Adj Close | Volume | Open | High | Low | Close | Adj Close | Volume | |
| Date | |||||||||||||||||||||
| 2019-10-23 | 60.5 | 60.8 | 60.3 | 60.8 | 59.1 | 75828800.0 | 88.1 | 88.5 | 87.1 | 88.1 | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| 2019-10-24 | 61.1 | 61.2 | 60.5 | 60.9 | 59.2 | 69275200.0 | 88.6 | 89.4 | 88.0 | 89.0 | ... | 60.4 | 60.6 | 49.0 | 11143800.0 | 119.2 | 119.6 | 118.5 | 119.1 | 111.7 | 2900300.0 |
| 2019-10-25 | 60.8 | 61.7 | 60.7 | 61.6 | 60.0 | 73477200.0 | 84.9 | 88.2 | 84.8 | 88.1 | ... | 59.2 | 60.4 | 48.9 | 15036400.0 | 119.0 | 119.3 | 118.2 | 119.0 | 111.7 | 2564300.0 |
| 2019-10-28 | 61.9 | 62.3 | 61.7 | 62.3 | 60.6 | 96572800.0 | 87.4 | 88.9 | 87.1 | 88.9 | ... | 60.0 | 60.2 | 48.7 | 14621400.0 | 119.2 | 119.7 | 118.5 | 119.2 | 111.8 | 3404600.0 |
| 2019-10-29 | 62.2 | 62.4 | 60.6 | 60.8 | 59.2 | 142839600.0 | 88.7 | 88.8 | 87.8 | 88.1 | ... | 60.1 | 60.2 | 48.7 | 10619900.0 | 118.5 | 118.7 | 117.1 | 117.2 | 109.9 | 4791100.0 |
5 rows × 120 columns
Finally, we merged the stocks dataframe and the global indexes dataframe on their, now the same, date index. The dataset is hierarchically indexed and we can see each column for each stock or index.
stock_dataset = dfStocks.join(dfIndexes)
stock_dataset = pd.merge(dfStocks, dfIndexes, on = 'Date', how ='inner').iloc[:1005]
stock_dataset.head()
| AAPL | AMZN | ... | WMT | S&P500 | DJIA30 | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Open | High | Low | Close | Adj Close | Volume | Open | High | Low | Close | ... | Adj Close | Volume | Open | High | Low | Close | Open | High | Low | Close | |
| Date | |||||||||||||||||||||
| 2019-10-24 | 61.1 | 61.2 | 60.5 | 60.9 | 59.2 | 69275200.0 | 88.6 | 89.4 | 88.0 | 89.0 | ... | 111.7 | 2900300.0 | 3014.78 | 3016.07 | 3000.42 | 3010.29 | 26893.93 | 26931.78 | 26714.34 | 26805.53 |
| 2019-10-25 | 60.8 | 61.7 | 60.7 | 61.6 | 60.0 | 73477200.0 | 84.9 | 88.2 | 84.8 | 88.1 | ... | 111.7 | 2564300.0 | 3003.32 | 3027.39 | 3001.94 | 3022.55 | 26789.61 | 27015.37 | 26765.68 | 26958.06 |
| 2019-10-28 | 61.9 | 62.3 | 61.7 | 62.3 | 60.6 | 96572800.0 | 87.4 | 88.9 | 87.1 | 88.9 | ... | 111.8 | 3404600.0 | 3032.12 | 3044.08 | 3032.12 | 3039.42 | 27040.33 | 27167.88 | 27028.71 | 27090.72 |
| 2019-10-29 | 62.2 | 62.4 | 60.6 | 60.8 | 59.2 | 142839600.0 | 88.7 | 88.8 | 87.8 | 88.1 | ... | 109.9 | 4791100.0 | 3035.39 | 3047.87 | 3034.81 | 3036.89 | 27061.07 | 27165.94 | 27039.76 | 27071.42 |
| 2019-10-30 | 61.2 | 61.3 | 60.3 | 60.8 | 59.1 | 124522000.0 | 88.0 | 89.1 | 88.0 | 89.0 | ... | 110.8 | 2996200.0 | 3039.74 | 3050.10 | 3025.96 | 3046.77 | 27110.71 | 27204.36 | 26999.64 | 27186.69 |
5 rows × 128 columns
Our goal is to use a single metric known as an index to represent equities across various industries. As a result, each industry will have representative indices that will aid in understanding how that specific industry or sector fared in relation to the world economy.
def get_stock_index(df,stock_name):
if stock_name == 'Tech':
temp_row = pd.DataFrame({100,100,100,100})
tech_stock_df = pd.concat((df.AAPL.Close,df.AMZN.Close,df.GOOG.Close,df.META.Close,df.MSFT.Close),join = 'inner',keys=['AAPL','AMZN','GOOG','META','MSFT'],axis=1)
tech_stock_df['TechIndex'] = 0.2*tech_stock_df.AAPL+0.2*tech_stock_df.AMZN+0.2*tech_stock_df.GOOG+0.2*tech_stock_df.META+0.2*tech_stock_df.MSFT
return tech_stock_df
elif stock_name == 'Pharma':
pharma_stock_df = pd.concat((df.JNJ.Close,df.PFE.Close,df.MRK.Close,df.BMY.Close,df.LLY.Close),join = 'inner',keys=['JNJ','PFE','MRK','BMY','LLY'],axis=1)
pharma_stock_df['PharmaIndex'] = 0.2*pharma_stock_df.JNJ+0.2*pharma_stock_df.PFE+0.2*pharma_stock_df.MRK+0.2*pharma_stock_df.BMY+0.2*pharma_stock_df.LLY
return pharma_stock_df
elif stock_name == 'Telecom':
telecom_stock_df = pd.concat((df['T'].Close,df.VZ.Close,df.TMUS.Close,df.CMCSA.Close,df.CHTR.Close),join = 'inner',keys=['T','VZ','TMUS','CMCSA','CHTR'],axis=1)
telecom_stock_df['TelecomIndex'] = 0.2*telecom_stock_df['T']+0.2*telecom_stock_df.VZ+0.2*telecom_stock_df.TMUS+0.2*telecom_stock_df.CMCSA+0.2*telecom_stock_df.CHTR
return telecom_stock_df
elif stock_name == 'FMCG':
fmcg_stock_df = pd.concat((df.PG.Close,df.KO.Close,df.PEP.Close,df.WMT.Close,df.CL.Close),join = 'inner',keys=['PG','KO','PEP','WMT','CL'],axis=1)
fmcg_stock_df['FMCGIndex'] = 0.2*fmcg_stock_df.PG+0.2*fmcg_stock_df.KO+0.2*fmcg_stock_df.PEP+0.2*fmcg_stock_df.WMT+0.2*fmcg_stock_df.CL
return fmcg_stock_df
else:
return NULL
def reindexing_stocks(df,stock_name,original_column_name):
df.reset_index(inplace=True)
new_column_name = stock_name + 'Reindex'
df[new_column_name] = 0
df.loc[0,new_column_name] = 100
for i in range(1,len(df)):
df.loc[i,new_column_name] = ((df[new_column_name][i-1].astype(float) * df[original_column_name][i].astype(float))/df[original_column_name][i-1].astype(float)).round(2)
df.set_index('Date',inplace=True)
Initially, we decided to examine how four industries performed throughout significant global events such as the first and second stages of COVID-19 and the Russia-Ukraine war. The simplest method for estimating performance was to examine stock prices, which account for everything. To bring all stock values and the world economy into a comparable range, we defined our indices. We created multiple indices, one for the global economy and one for each industry. We now construct a time series graph for the global and sector indices and take into account the stock prices over the period that saw COVID-19 and the Russia-Ukraine war.
#creating stock indexes as metric for all the sectors
techstock_df = get_stock_index(stock_dataset,'Tech')
pharmastock_df = get_stock_index(stock_dataset,'Pharma')
telecomstock_df = get_stock_index(stock_dataset,'Telecom')
fmcgstock_df = get_stock_index(stock_dataset,'FMCG')
sp500_df = stock_dataset['S&P500']['Close'].to_frame()
djia30_df = stock_dataset['DJIA30']['Close'].to_frame()
#reindexing stock indexes to calculate their change in price
reindexing_stocks(techstock_df,'Tech','TechIndex')
reindexing_stocks(pharmastock_df,'Pharma','PharmaIndex')
reindexing_stocks(telecomstock_df,'Telecom','TelecomIndex')
reindexing_stocks(fmcgstock_df,'FMCG','FMCGIndex')
#reindexing global stocks to calculate their change in value
reindexing_stocks(sp500_df,'S&P500','Close')
reindexing_stocks(djia30_df,'DJIA30','Close')
# Create bins for the date values
techstock_df.index = pd.to_datetime(techstock_df.index)
pharmastock_df.index = pd.to_datetime(pharmastock_df.index)
telecomstock_df.index = pd.to_datetime(telecomstock_df.index)
fmcgstock_df.index = pd.to_datetime(fmcgstock_df.index)
sp500_df.index = pd.to_datetime(sp500_df.index)
djia30_df.index = pd.to_datetime(djia30_df.index)
date_bins = pd.date_range(start=techstock_df.index.min(), end=techstock_df.index.max())
# Assign bins to each date
techstock_df['date_bins'] = pd.cut(techstock_df.index, bins=date_bins)
pharmastock_df['date_bins'] = pd.cut(pharmastock_df.index, bins=date_bins)
telecomstock_df['date_bins'] = pd.cut(telecomstock_df.index, bins=date_bins)
fmcgstock_df['date_bins'] = pd.cut(fmcgstock_df.index, bins=date_bins)
sp500_df['date_bins'] = pd.cut(sp500_df.index, bins=date_bins)
djia30_df['date_bins'] = pd.cut(djia30_df.index, bins=date_bins)
data = pd.concat([techstock_df.TechReindex, pharmastock_df.PharmaReindex, telecomstock_df.TelecomReindex, fmcgstock_df.FMCGReindex,sp500_df['S&P500Reindex'],
djia30_df['DJIA30Reindex']], axis=1, ignore_index=True)
data.columns = ['Tech','Pharma','Telecom','FMCG','S&P500','DJIA30']
# defining variables for the dimensions of the charts to follow
height_of_chart = 600
width_of_chart = 1400
fig = px.line(data, x=data.index, y=['Tech','Pharma','Telecom','FMCG','S&P500','DJIA30'], title="Different Sectors v/s Global Economy",
height=height_of_chart).update_layout( xaxis_title="Month-Year", yaxis_title="Stock Value", legend=dict(
title="Stocks"),plot_bgcolor='white')
fig.update_xaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.update_yaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.update_traces(line=dict(color='red'), selector=dict(name='Tech'))
fig.update_traces(line=dict(color='#0504aa'), selector=dict(name='Pharma'))
fig.update_traces(line=dict(color='gold'), selector=dict(name='Telecom'))
fig.update_traces(line=dict(color='magenta'), selector=dict(name='FMCG'))
fig.update_traces(line=dict(dash='dash',color='black'), selector=dict(name='S&P500'))
fig.update_traces(line=dict(dash='dash',color='black'), selector=dict(name='DJIA30'))
fig.show()
The increase in Tech Industry stock prices can be attributed to people relying on digital technologies and the fact that more people were working from home and students attending courses online during the pandemic period. The period of the Russia-Ukraine war is seen as a downfall for the tech sector whereas the Pharma Sector boomed. This was due to the lifting of the lockdown restrictions and so people started commuting to offices and so the dependency on digital services such as Zoom calls and online newspapers decreased. The Tech companies had over hired during the COVID period due to the high demand for their digital services then but now as things returned to normal the demand decreased leading to layoffs. Also, this was the period when vaccines were released to the public and mass vaccination drives took place which led to a boom in the Pharmaceutical Industry.
In the above analysis we saw that the technology sector performed well and was bullish when the world was suffering a setback due to the pandemic. This makes the Tech sector even more interesting to analyze and study about how it survived the impact of the pandemic and on top of that it's stock prices were well above what they were before the pandemic had hit.
We will now study the Technology sector in detail. We have shortlisted the top-performing stocks that dominate the technology sector and will be analyzing them along with the Tech sector index we created using the stock prices of these five stocks.
We are plotting a time series graph of Apple, Amazon, Google, Meta, Microsoft, and the TechReindex to get a fair gist of the individual stock performance relative to the sector as a whole.
#reindexing stock indexes to calculate their change in price
reindexing_stocks(techstock_df,'AAPL','AAPL')
reindexing_stocks(techstock_df,'AMZN','AMZN')
reindexing_stocks(techstock_df,'GOOG','GOOG')
reindexing_stocks(techstock_df,'META','META')
reindexing_stocks(techstock_df,'MSFT','MSFT')
techstock_df.head()
| AAPL | AMZN | GOOG | META | MSFT | TechIndex | TechReindex | date_bins | AAPLReindex | AMZNReindex | GOOGReindex | METAReindex | MSFTReindex | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Date | |||||||||||||
| 2019-10-24 | 60.9 | 89.0 | 63.0 | 186.4 | 139.9 | 107.84 | 100.00 | NaN | 100.00 | 100.00 | 100.00 | 100.00 | 100.00 |
| 2019-10-25 | 61.6 | 88.1 | 63.3 | 187.9 | 140.7 | 108.32 | 100.45 | (2019-10-24, 2019-10-25] | 101.15 | 98.99 | 100.48 | 100.80 | 100.57 |
| 2019-10-28 | 62.3 | 88.9 | 64.5 | 189.4 | 144.2 | 109.86 | 101.88 | (2019-10-27, 2019-10-28] | 102.30 | 99.89 | 102.38 | 101.60 | 103.07 |
| 2019-10-29 | 60.8 | 88.1 | 63.1 | 189.3 | 142.8 | 108.82 | 100.92 | (2019-10-28, 2019-10-29] | 99.84 | 98.99 | 100.16 | 101.55 | 102.07 |
| 2019-10-30 | 60.8 | 89.0 | 63.1 | 188.2 | 144.6 | 109.14 | 101.22 | (2019-10-29, 2019-10-30] | 99.84 | 100.00 | 100.16 | 100.96 | 103.36 |
fig = px.line(techstock_df, x=techstock_df.index, y=['AAPLReindex','AMZNReindex','GOOGReindex','METAReindex','MSFTReindex','TechReindex'], title="Individual Tech stock performance",
height=height_of_chart).update_layout( xaxis_title="Month-Year", yaxis_title="Stock Value", legend=dict(
title="Stocks"),plot_bgcolor='white')
fig.update_xaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.update_yaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.update_traces(line=dict(dash='dash',color='black'), selector=dict(name='TechReindex'))
fig.update_traces(line=dict(color='red'), selector=dict(name='AAPLReindex'))
fig.update_traces(line=dict(color='gold'), selector=dict(name='AMZNReindex'))
fig.update_traces(line=dict(color='#0504aa'), selector=dict(name='GOOGReindex'))
fig.update_traces(line=dict(color='mediumpurple'), selector=dict(name='METAReindex'))
fig.update_traces(line=dict(color='green'), selector=dict(name='MSFTReindex'))
fig.update_traces(line=dict(dash='dash',color='black'), selector=dict(name='TechReindex'))
fig.show()
During the pandemic period, all the tech companies prospered after a small initial setback as digital services were in demand as people were stranded at their homes. We see a dip in the stock prices of Meta during the Russia-Ukraine war period. But surprisingly Microsoft survives it and maintains its price without getting much affected. Meta bounced back after the crash it suffered in February 2022 and reached close to Microsoft's stock price.
Amazon's stock price has also outperformed the TechReindex since the start of the pandemic. This is likely due to the company's strong position in the e-commerce market. The pandemic led to a surge in online shopping, and Amazon was well-positioned to meet this demand. In addition, Amazon has benefited from its strong cloud computing business, Amazon Web Services (AWS).
Meta's stock price surge can be attributed to a combination of factors, including a strong rebound from a previous decline, successful cost-cutting measures, the success of Reels and its monetization initiatives, return on AI investments, positive analyst reports and market sentiment shift, and potentially technical factors.
Resilience of technology sector: The pandemic led to an increased reliance on digital technologies for work, education, entertainment, and communication. This boosted demand for products and services offered by tech companies, leading to revenue and profit growth. As a reason in the above graph we can see a clear surge in all the tech stocks.
Adaptability to remote work: Tech companies were well-positioned to adapt to remote work environments, as they already had the infrastructure and tools in place to support distributed teams. This allowed them to maintain productivity and continue operations while other industries faced disruptions. That is why companies like META, Amazon and Microsoft have remained bullish.
Overall, the technology sector's performance during the pandemic showcases its resilience, adaptability, and potential for long-term growth.
Given its proximity to the TechReIndex and its history of highs and lows, we thought it would be interesting to examine the stock price of Amazon. It increased during the peak of digital services during the pandemic. Then, in 2022, there are issues with Amazon Web Services and its supply chain, which causes its price to decrease before stabilizing. In order to thoroughly examine Amazon's activity, we will now plot the company using the Tech and Global indexes.
dataframe = pd.concat([techstock_df.AMZNReindex,techstock_df.TechReindex,sp500_df['S&P500Reindex'],djia30_df['DJIA30Reindex']],axis=1)
dataframe.head()
| AMZNReindex | TechReindex | S&P500Reindex | DJIA30Reindex | |
|---|---|---|---|---|
| Date | ||||
| 2019-10-24 | 100.00 | 100.00 | 100.00 | 100.00 |
| 2019-10-25 | 98.99 | 100.45 | 100.41 | 100.57 |
| 2019-10-28 | 99.89 | 101.88 | 100.97 | 101.06 |
| 2019-10-29 | 98.99 | 100.92 | 100.89 | 100.99 |
| 2019-10-30 | 100.00 | 101.22 | 101.22 | 101.42 |
fig = px.line(dataframe, x=dataframe.index, y=['AMZNReindex','TechReindex','S&P500Reindex','DJIA30Reindex'], title="Amazon v/s Other Tech Stocks",
height=height_of_chart).update_layout( xaxis_title="Month-Year", yaxis_title="Stock Value", legend=dict(
title="Stocks"),plot_bgcolor='white')
fig.update_xaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.update_yaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
fig.show()
Tech Sector Outperformance:
The tech sector demonstrated remarkable resilience, surpassing the global economy's performance during the early stages of the pandemic's uncertainty.
Initial downturn and tech rebound including Amazon:
Initially, the stocks and market experienced a downturn trend. Towards the end of Q1 and the start of Q2, both Amazon and tech sector saw huge surge in which Amazon emerged as a standout performer.
Widening performance gap:
The performance gap between Amazon and other tech companies continued to widen, stressing Amazon's exceptional ability to navigate and excel in challenging circumstances.
E-commerce, Entertainment, and AWS as Dire Requirements:
The lockdowns heightened the importance of E-commerce, Entertainment, and Amazon Web Services (AWS) as essential services. The necessity for online shopping, digital content consumption, and cloud-based solutions became pronounced during a period where physical interactions were limited. This shift in demand underlines the critical role these segments played in facilitating daily life and business operations.
Tech Sector and Digitization Significance:
The tech sector's significance during the lockdowns was underscored by the broader importance of digitization. As physical spaces closed down, various aspects of life, work, and entertainment shifted to digital platforms. This accelerated digitization became a defining factor, emphasizing the tech sector's role as an enabler of remote work, digital communication, and online experiences.
Digitization Impact on Activities:
The way we conduct activities underwent a transformative shift through digitization. Daily tasks, previously reliant on physical presence, adapted to virtual alternatives. Online newspapers and Zoom meetings exemplify this trend, highlighting the tech sector's pivotal role in providing digital solutions that sustained connectivity, information circulation, and business operations.
How Amazon stood out as a standalone performer:
Amazon emerged as the biggest winner during the pandemic by capitalizing on the surge in demand for online shopping and services. As lockdowns restricted physical interactions, consumers turned to Amazon for a wide array of products, making the e-commerce giant an indispensable resource. The company's strategic investments, rapid adaptability, and robust infrastructure allowed it to not only navigate challenges but also thrive in the evolving digital landscape. Amazon's dominance in e-commerce, coupled with the success of its cloud computing arm (AWS) and entertainment services, positioned it as a key beneficiary in a world increasingly reliant on digital solutions.
dfx = stock_dataset['S&P500'].copy()
dfy = stock_dataset['AMZN'].copy()
x = dfx['Close']
y = dfy['Close']
dfx['color'] = ['blue'] * 160 + ['red'] * 39 + ['orange'] * 806
sns.set_style('whitegrid')
fig, axes = plt.subplots()
fig.set_size_inches(20, 5)
axes = sns.regplot(x=x, y=y, scatter_kws={'color':list(dfx['color'].values)})
axes.set(xlabel = 'S&P 500 Close Prices', ylabel = 'AMZN Close Prices')
axes.set_title('AMZN vs S&P Close Prices')
Text(0.5, 1.0, 'AMZN vs S&P Close Prices')
Amazon's stock witnessed a nearly twofold increase during the initial wave of the COVID-19 pandemic. However, as the pandemic concluded, the stock underwent a correction, relinquishing its pandemic-driven gains and reverting to pre-pandemic levels.
Subsequently, Amazon grappled with a slowdown in its core retail business, necessitating operational adjustments to address the deceleration. This highlighted the enduring impact of the COVID-19 pandemic on Amazon's stock price, underscoring the company's reliance on the evolving landscape of online consumer behavior.
Initial Public Offering - June 2020 (Blue): Amazon witnessed a significant surge in its stock price during the initial wave of COVID-19. This period saw the stock nearly double in value, primarily driven by a shift in consumer behavior towards online shopping and streaming services due to stay-at-home mandates. To accommodate the increased demand, Amazon hired additional personnel and implemented new operational procedures.
June 2020 - August 2020 (Red): Amazon maintained its strong performance throughout the second wave of COVID-19 in 2021. Consumer preference for the e-retailer remained high, contributing to the stock's resilience. However, the company encountered challenges such as supply chain disruptions and rising delivery costs. Despite these obstacles, Amazon's strategic investments made in response to the pandemic helped its stock thrive. Higher net sales here reflect increased demand, particularly as people are staying at home.
August 2020 - Present (Orange): With the conclusion of the COVID-19 waves, Amazon's stock performance displayed a mixed trajectory. While the company relinquished all pandemic-related gains, returning to pre-pandemic levels, it also faced a deceleration in its core retail business growth. This is because of increased fulfillment costs due to increased employee hiring and costs to maintain safe workspaces. This prompted a scaling back of operations after the expansive growth experienced during the pandemic.
Amazon's stock witnessed a remarkable surge during the initial COVID-19 wave in 2020, nearly doubling in value as consumers turned to online shopping and streaming services amid stay-at-home mandates. Throughout the second wave, Amazon maintained robust performance despite challenges such as supply chain disruptions and escalating delivery costs. Post-pandemic, the stock retreated to pre-COVID levels, reflecting a deceleration in retail growth due to increased fulfillment costs arising from expanded hiring and safety measures. Amazon stock's dynamic journey highlights Amazon's adaptability and strategic resilience in a changing business landscape.
When looking at investing into a stock, many investors will look at the volatility of the stock - or the rate of how much the stock price increases and decreases over a certain period of time. In order to look at the volatility of AMZN, we will be using a Bollinger Bands analysis. This analysis focuses on the average price of the stock, calculated every 20 days throughout the time period, and the upper and lower bands which represent values 2 standard deviations away from the average. When the price touches the upper band, it suggests that the stock is overbought, meaning that the stock is trading in the upper range of its recent price range. When the price touches the lower band, it suggests the stock is oversold, or trading in the lower range of its recent price range. Depending on the type of investor (risky or safe), volatility can make a big difference in their decision to invest. We are going to plot the Bollinger Bands for AMZN during lockdown 1.
def createBB(df, stockname, timeperiod):
# Creating a copy of the dataframe so we can add columns
df = df.copy()
# Calculating 20 day simple moving average and the standard deviation for that average
df.loc[:,'Mean'] = df['Close'].rolling(20).mean()
df.loc[:,'Stdev'] = df['Close'].rolling(20).std()
# Dropping null values
df.dropna(inplace = True)
# Calculating upper band and lower band (mean +/- 2 stdev)
df.loc[:,'Upper Band'] = df['Mean'] + 2 * df['Stdev']
df.loc[:,'Lower Band'] = df['Mean'] - 2 * df['Stdev']
df_layout = go.Layout(title = f'{stockname} Bollinger Bands {timeperiod}',plot_bgcolor='white',height=height_of_chart)
# Candlestick Bollinger Band chart
df_display = go.Figure(data=[go.Candlestick(x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name = 'Candlestick'),
# First line chart: Simple Moving Average
go.Scatter(x = df.index,
y = df['Mean'],
name = 'Simple Moving Average',
mode = 'lines'),
# Second line chart: Upper Band
go.Scatter(x = df.index,
y = df['Upper Band'],
name = 'Upper Band',
mode = 'lines'),
# Third line chart: Lower Band
go.Scatter(x = df.index,
y = df['Lower Band'],
name = 'Lower Band',
mode = 'lines')],
layout = df_layout)
df_display.update_xaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
df_display.update_yaxes(mirror=True,gridcolor='lightgray',showline=True,linecolor='black')
df_display.show()
createBB(stock_dataset['AMZN'],'AMZN', 'Over Last 4 Years')
Amazon's stock price oscillates within the Bollinger Bands, indicating inherent tech sector volatility. This volatility is further amplified by two major global crises: the COVID-19 pandemic and the Russo-Ukrainian war.
The pandemic initially fueled Amazon's growth due to increased online activity, reflected in wider Bollinger Bands. However, post-pandemic adjustments and supply chain disruptions caused stock price fluctuations and narrowed the bands.
Overall Amazon's stock price is heavily influenced by major global events and exhibits periods of high volatility.
As we can see in the chart, the average price hugged the lower band for the first half of March (the start of the lockdown) and continued to decrease. This indicates that the stock was oversold, which can seem like an indicator to buy because of the low price, but sometimes investors see it as a sign of a stock continuing to fall, especially during a global crisis.
Around mid-March, the stock price shot up again until the end of April when it began occasionally hugging the upper band. When this happens, it is typically a sign that one should sell their stock, as the price will soon decrease. However, the price seemed to remain steady in May and increased in further into June.
Post-Pandemic Adjustment:
As life normalized, Amazon faced the challenge of scaling back operations and adapting to changing consumer behavior. This led to a period of volatility as the market assessed the company's future growth prospects.
Supply Chain Disruptions:
Global supply chain disruptions caused by the pandemic further impacted Amazon's stock price. Wider Bollinger Bands mirrored the market's uncertainty about the company's ability to navigate these challenges.
The Russo-Ukrainian War and its Ripples: Economic Uncertainty: The war exacerbated existing economic headwinds like inflation and rising interest rates. This heightened investor uncertainty, leading to increased volatility in the tech sector and wider Bollinger Bands for Amazon's stock. Energy Price Fluctuations: The war caused energy prices to spike, impacting Amazon's operational costs and profit margins. This negatively affected investor sentiment and contributed to stock price fluctuations. Shifting Consumer Priorities: The war shifted consumer priorities, leading to reduced spending on non-essential items. This impacted Amazon's core retail business and contributed to a narrowing of the Bollinger Bands as market volatility subsided.
In the wake of unprecedented global events, such as the COVID-19 pandemic and the Russia-Ukraine war, our project seeks to uncover the complex dynamics affecting the performance of top stocks in the technology, pharmaceuticals, telecommunication, and FMCG sectors. The analysis covers from October 2019 to October 2023, with an in-depth look at the following global crisis:
Lockdown 1:- March 2020 to July 2020,
Lockdown 2 (Omicron):- November 2021 to February 2022,
Ukraine War:- 24 February 2022 till date.
A critical period that reveals the resilience and vulnerability of these industries.
The Relativity Chart provides a macro perspective, revealing how the tech industry has outperformed during the crisis due to its increased reliance on digital technologies. The pharmaceutical industry has thrived during the war, driven by vaccine development, while fast-moving consumer goods have faced challenges as lockdowns impacted retail.
Within the Technology sector, a detailed exploration of top-performing stocks like Apple, Amazon, Google, Meta, and Microsoft showcases Amazon's remarkable resilience. The e-commerce giant has capitalized on the surge in online shopping and the critical role of AWS during the lockdown to emerge as a strong performer.
The movement in Amazon's stock price reflects the changing landscape of consumer behavior. Initially, its critical role was highlighted by a nearly tripling of growth during the pandemic. After the pandemic, challenges such as supply chain disruptions prompted operational adjustments, leading to inventory withdrawals.
Amazon’s Bollinger Bands analysis provides insights into the stock’s volatility during the lockdown. The lower range during the initial lockdown suggested oversoldness, while the post-pandemic correction and global crisis-induced volatility signaled the stock's sensitivity to major events.
As the Russia-Ukraine war unfolds, Amazon faces additional challenges, including soaring energy prices and shifting consumer priorities. These factors contribute to share price volatility, underscoring the interconnectedness of geopolitical events and stock market dynamics.
Overall, the project provides valuable insights into the nuanced responses of different industries and stocks to the global crisis. The importance of the tech industry in promoting digitalization and the transformative impact of the pandemic on consumer behavior is clear. Amazon's journey is a microcosm of a market heavyweight's ability to adapt, its strategic resilience, and the impact of external events.
Investors and policymakers can draw important lessons from these analyses to help make informed decisions in uncertain times. The project emphasizes the importance of adaptability, technological resilience, and a comprehensive understanding of the intricate interplay between global events and financial markets. As the world continues to grapple with unforeseen challenges, this research provides valuable guidance to those seeking to understand and navigate the changing global economic landscape.
[1] Professor's notebooks as guidance throughout the notebook
[2] Data Sources:
[a] https://finance.yahoo.com/
[b] https://www.marketwatch.com/
[3] Market Research for AMZN - 10 Q for lockdown 1 period - https://www.sec.gov/Archives/edgar/data/1018724/000101872420000021/amzn-20200630.htm
[4] Research for AMZN - 10 K for 2020 - https://www.sec.gov/Archives/edgar/data/1018724/000101872421000004/amzn-20201231.htm
[5] McKinsey Report - To understand impact of Covid - https://www.mckinsey.com/capabilities/strategy-and-corporate-finance/our-insights/how-covid-19-has-pushed-companies-over-the-technology-tipping-point-and-transformed-business-forever
[6] Financial Edge - To understand Rebasing / Reindexing - https://www.fe.training/free-resources/asset-management/rebasing-stock-prices-to-100/
[7] Data Visualizations:
[a] For Plotly Candle stick graphs - https://plotly.com/python/candlestick-charts/
[b] For Plotlty Line Graphs - https://plotly.com/python/line-charts/